package cn.qhuan.modules.service.impl;


import cn.qhuan.modules.constos.PageResponseResult;
import cn.qhuan.modules.constos.StatusConstos;

import cn.qhuan.modules.dtos.*;

import cn.qhuan.modules.entity.*;
import cn.qhuan.modules.mapper.*;
import cn.qhuan.modules.service.IWorksService;

import cn.qhuan.modules.vo.WorksVO;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 作品表
 * @Author: 司翔宇
 * @Date:   2020-12-18
 * @Version: V1.0
 */
@Service
public class WorksServiceImpl extends ServiceImpl<WorksMapper, Works> implements IWorksService {

    @Autowired
    private WorksMapper worksMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArtistMapper artistMapper;

    @Autowired
    private DynastyMapper dynastyMapper;

    @Autowired
    private WorksCategoryMapper worksCategoryMapper;

    @Override
    public Result<?> updateStatus(WorksAuthDto dto, Integer type) {
        //1.检查参数
        if (dto ==null || dto.getId() == null ){
            return Result.error("缺少参数");
        }
        //2.查询作品信息
        Works qhWorks = worksMapper.selectById(dto.getId());
        if (qhWorks == null){
            return Result.error("作品不存在");
        }
        //3.审核失败
        if (type.equals(StatusConstos.STATUS_FAIL)){
            updateWorks(qhWorks,StatusConstos.STATUS_FAIL,dto.getMsg());
        }else if (type.equals(StatusConstos.STATUS_PASS)){
            updateWorks(qhWorks,StatusConstos.STATUS_PASS,"审核通过");
        }
        return Result.OK("修改成功");
    }

    @Override
    public Result<?> updateShowStatus(WorksShowDto showDto, Integer type) {
        //1.检查参数
        if (showDto == null || showDto.getId() == null ){
            return Result.error("缺少参数");
        }
        //2.查询作品信息
        Works qhWorks = worksMapper.selectById(showDto.getId());
        if (qhWorks == null ){
            return Result.error("作品不存在");
        }
        //修改作品展示状态
        //不显示
        if (type.equals(StatusConstos.HIDDEN_STATUS)){
            updateShowWorks(qhWorks,StatusConstos.HIDDEN_STATUS);

        }else if (type.equals(StatusConstos.SHOW_STATUS)){
            updateShowWorks(qhWorks,StatusConstos.SHOW_STATUS);
        }
        return Result.OK("修改成功");
    }



    @Override
    public Result<?> loadNewWorks(WorksTimeDto dto) {
        //检查参数
        if (dto == null ){
            return Result.error("缺少参数");
        }
        //分页检查
        dto.checkParam();
        IPage pageParam = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<Works> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        if (WorksTimeDto.getNowTime() != null){
            lambdaQueryWrapper.notIn(Works::getStatus,0,2).notIn(Works::getShowFront,1)
                    .notIn(Works::getDelFlag,1).le(Works::getCreateTime,WorksTimeDto.getNowTime()).orderByDesc(Works::getCreateTime);
        }
        IPage pageList = page(pageParam, lambdaQueryWrapper);
        PageResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(), (int) pageList.getTotal());
        responseResult.setResult(pageList.getRecords());
        return responseResult;
    }

    @Override
    public Result<?> addWorksToType(String uuid, String worksId, String typeId) {
        //参数判断
        if (uuid == null || worksId == null || typeId == null){
            return Result.error("缺少参数");
        }
        if (worksMapper.selectWorksCountToType(worksId)== 0){
            worksMapper.addWorksToType(uuid,worksId,typeId);
            return Result.OK("类别设置成功");
        }else {
            worksMapper.deleteTypeAssociation(worksId);
            worksMapper.addWorksToType(uuid,worksId,typeId);
            return Result.OK("类别修改成功");

        }

    }
    @Override
    public Result<?> addWorksToTg(String uuid, String worksId, String tagId) {
       if (uuid == null || worksId == null || tagId == null){
           return Result.error("缺少参数");
       }
       if (worksMapper.selectWorksCountToTag(worksId)==0){
           worksMapper.addWorksToTag(uuid, worksId, tagId);
           return Result.OK("标签设置成功");
       }else {
           worksMapper.deleteTagAssociation(worksId);
           worksMapper.addWorksToTag(uuid, worksId, tagId);
           return Result.OK("标签修改成功");
       }

    }

    @Override
    public Result<?> addWorksToSpec(String uuid, String worksId, String specId) {
        //参数判断
        if (uuid == null || worksId == null || specId == null){
            return Result.error("缺少参数");
        }
        if (worksMapper.selectWorksCountToSpec(worksId) == 0){
            worksMapper.addWorksToSpec(uuid,worksId,specId);
            return Result.OK("专题设置成功");
        }else {
            worksMapper.deleteSpecialAssociation(worksId);
            worksMapper.addWorksToSpec(uuid,worksId,specId);
            return Result.OK("专题修改成功");
        }

    }

    @Override
    public Result<?> addWorksToExhi(String uuid,String worksId, String exhiId) {
        //参数判断
        if (uuid == null || worksId == null || exhiId == null){
            return Result.error("缺少参数");
        }
        if (worksMapper.selectWorksCountToExhi(worksId) == 0){
            worksMapper.addWorksToExhi(uuid,worksId,exhiId);
            return Result.OK("展厅设置成功");
        }else {
            worksMapper.deleteExhiAssociation(worksId);
            worksMapper.addWorksToExhi(uuid,worksId,exhiId);
            return Result.OK("展厅修改成功");
        }
    }


    @Override
    public Result<?> addWorksToDynasty(String uuid, String worksId, String dynastyId) {
        //参数判断
        if (uuid == null || worksId == null || dynastyId == null ){
            return Result.error("缺少参数");
        }
        if (worksMapper.selectWorksCountToDyn(worksId) == 0){
            Works qhWorks = worksMapper.selectById(worksId);
            qhWorks.setDynastyId(dynastyId);
            worksMapper.updateById(qhWorks);
            worksMapper.addWorksToDynasty(uuid,worksId,dynastyId);
            return Result.OK("朝代设置成功");
        }else {
            Works qhWorks = worksMapper.selectById(worksId);
            qhWorks.setDynastyId(dynastyId);
            worksMapper.updateById(qhWorks);
            worksMapper.deleteDynastyAssociation(worksId);
            worksMapper.addWorksToDynasty(uuid,worksId,dynastyId);
            return Result.OK("朝代修改成功");

        }

    }

    @Override
    public Result<?> addWorksToArtist(String uuid, String worksId, String artistId) {
        //参数判断
        if (uuid == null || worksId == null || artistId == null ){
            return Result.error("缺少参数");
        }
        if (worksMapper.selectWorksCountToArt(worksId) == 0){
            Works qhWorks = worksMapper.selectById(worksId);
            qhWorks.setArtistId(artistId);
            worksMapper.updateById(qhWorks);
            worksMapper.addWorksToArtistId(uuid,worksId,artistId);

            return Result.OK("艺术家设置成功");
        }else {
            Works qhWorks = worksMapper.selectById(worksId);
            qhWorks.setArtistId(artistId);
            worksMapper.updateById(qhWorks);
            worksMapper.deleteArtistAssociation(worksId);
            worksMapper.addWorksToArtistId(uuid,worksId,artistId);
            return Result.OK("艺术家修改成功");
        }

    }

    @Override
    public Result<?> selectCountByKeyWord(WorksDto dto) {
        if (dto.getKeyword() == null ){
            return Result.error("缺少参数");
        }
        if(StringUtils.isNotBlank(dto.getKeyword())){
            dto.setKeyword("%"+dto.getKeyword() +"%");
        }
        Integer count = worksMapper.selectCountByKeyWord(dto);
        return Result.OK(count);
    }

    @Override
    public Result<?> selectWorksCount() {
        //查询所有作品的数量
        Integer count = worksMapper.selectWorksCount();
        if (count > 0){
            return Result.OK(count);
        }else {
            return Result.error("暂无作品");
        }
    }

    @Override
    public Result<?> findWorksVo(Integer id) {
        //参数判断
        if (id == null ){
            return Result.error("缺少参数");
        }
        //查询作品信息
        Works qhWorks = getById(id);
        //查询作者
        Artist artist= null ;
        if (qhWorks != null && qhWorks.getArtistId() != null ){
            artist = artistMapper.selectById(qhWorks.getArtistId());
        }
        Dynasty dynasty =null ;
        if (qhWorks != null && qhWorks.getDynastyId()!=null){
            dynasty =dynastyMapper.selectById(qhWorks.getDynastyId());
        }
        //查询类别
        WorksCategory worksCategory = null ;
        if (id != null){
             worksCategory = worksCategoryMapper.findByWorksId(id.toString());
        }
        //查询标签
        Tag tag= null ;
        if (id != null ){
             tag = tagMapper.findByWorksId(id.toString());
        }
        //封装vo结果进行返回
        WorksVO worksVO =new WorksVO();
        BeanUtils.copyProperties(qhWorks,worksVO);
        if (artist != null && dynasty != null && worksCategory != null && tag != null ){
            worksVO.setAuthorName(artist.getName());
            worksVO.setDynastyName(dynasty.getName());
            worksVO.setTagName(tag.getName());
            worksVO.setTypeName(worksCategory.getName());

        }
        return Result.OK(worksVO);
    }

    @Override
    public Result<?> findList(WorksDto dto) {
        //设置分页条件
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getKeyword())){
            dto.setKeyword("%"+dto.getKeyword()+"%");
        }
        List<WorksVO> listAndPage = worksMapper.findListAndPage(dto);
        //统计数据
        int count = worksMapper.findListCount(dto);
        //凤凰结果进行返回
        PageResponseResult pageResponseResult =new PageResponseResult(dto.getPage(),dto.getSize(),count);
        pageResponseResult.setResult(listAndPage);
        return pageResponseResult;


    }

    @Override
    public Result<?> saveWorks(WorksDtoVo dto) {
        //判断参数
        if (dto != null ){
            save(dto);
            addWorksToTg(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getTagId());
            addWorksToSpec(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getSpecialId());
            addWorksToArtist(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getArtistId());
            addWorksToDynasty(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getDynastyId());
            addWorksToType(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getTypeId());
            addWorksToExhi(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getExhiId());
            return Result.OK("添加成功");
        }

        return Result.error("添加失败");
    }

    @Override
    public Result<?> editWorks(WorksDtoVo dto) {
        //判断参数
        if ( dto == null || dto.getId() == null){
            return Result.error("缺少参数");
        }
        updateById(dto);
        addWorksToTg(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getTagId());
        addWorksToSpec(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getSpecialId());
        addWorksToArtist(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getArtistId());
        addWorksToDynasty(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getDynastyId());
        addWorksToType(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getTypeId());
        addWorksToExhi(String.valueOf(UUID.randomUUID()),dto.getId(),dto.getExhiId());
        return Result.OK("编辑成功");
    }

    /**
     * 修改作品信息
     * @param qhWorks
     * @param status
     * @param msg
     */
    private void updateWorks (Works qhWorks,Integer status, String msg){
        qhWorks.setStatus(status);
        qhWorks.setRefusedReason(msg);
        qhWorks.setAuditTime(new Date());
        worksMapper.updateById(qhWorks);
    }

    /**
     * 修改作品是否在前台显示状态
     * @param qhWorks
     * @param showStatus
     */
    private void updateShowWorks(Works qhWorks,Integer showStatus){
        qhWorks.setShowFront(showStatus);
        worksMapper.updateById(qhWorks);
    }
}
